<template>
  <div>
    <el-form :inline="true">
      <el-form-item label="统计日期:">
        <el-date-picker
          v-model="form.rangeDate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :plain="type !== 'today'" @click="changeDate('today')">今天</el-button>
        <el-button type="primary" :plain="type !== 'week'" @click="changeDate('week')">近七天</el-button>
        <el-button type="primary" :plain="type !== 'month'" @click="changeDate('month')">近三十天</el-button>
      </el-form-item>
      <el-form-item>
        <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" :span-method="arraySpanMethod" style="width: 100%;">
      <el-table-column prop="itemName" label="项目" min-width="100" align="center" />
      <el-table-column label="呼入电话统计" align="center">
        <el-table-column prop="totalCallIn" label="呼入电话" min-width="90" align="center">
          <template slot-scope="{row}">
            <div v-if="row.rowThree" class="red">{{ row.answerRate }}</div>
            <div v-else>{{ row.totalCallIn }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="userAbandon" label="用户取消" min-width="90" align="center" />
        <el-table-column prop="toDivert" label="值班电话" min-width="90" align="center" />
        <el-table-column prop="toStation" label="坐席电话" min-width="90" align="center" />
      </el-table-column>
      <el-table-column label="座席电话统计" align="center">
        <el-table-column prop="toStationNoqueue" label="未进入队列" min-width="120" align="center" />
        <el-table-column prop="toStationQueue" label="进入队列" min-width="120" align="center" />
        <el-table-column prop="ztl" label="直通率" min-width="180" align="center">
          <template slot-scope="{row}">
            <div v-if="row.rowOne" class="red">{{ row.passRate }}</div>
            <div v-else class="row-cell">
              <div class="cell-l">{{ row.abandonNoservice }}</div>
              <div class="cell-r">{{ row.toBlackList }}</div>
            </div>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="时长统计(s)" align="center">
        <el-table-column prop="averageTalktime" label="平均通话" min-width="90" align="center" />
        <el-table-column prop="averageWaittimeOfTalk" label="应答电话平均等待" min-width="130" align="center" />
      </el-table-column>
    </el-table>
    <div ref="echart" class="echart" />
  </div>
</template>

<script>
  import echarts from 'echarts'
  import dayjs from 'dayjs'
  import { addResizeListener, removeResizeListener } from 'element-ui/src/utils/resize-event'
  import { phoneNew, phoneRate } from '@/api'
  export default {
    name: 'overallSituation',
    data() {
      return {
        form: {
          rangeDate: []
        },
        type: '',
        tableData: []
      }
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      this.chart.dispose()
      this.chart = null
      removeResizeListener(this.$refs.echart, this.doResize)
    },
    created() {
      this.getData()
    },
    mounted() {
      this.form.rangeDate = [new Date(), new Date()]
    },
    methods: {
      changeDate(type) {
        this.type = type
        if (type === 'today') {
          this.form.rangeDate = [new Date(), new Date()]
          this.getData()
        }
        if (type === 'week') {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          this.form.rangeDate = [start, end]
          this.getData()
        }
        if (type === 'month') {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
          this.form.rangeDate = [start, end]
          this.getData()
        }
      },
      search() {
        this.getData()
      },
      async getData() {
        const params = {
          // corpSN: this.$store.getters.userInfo.corpSN,
          startDt: dayjs(this.form.rangeDate[0]).format('YYYY-MM-DD'),
          endDt: dayjs(this.form.rangeDate[1]).format('YYYY-MM-DD')
        }
        const res = await phoneNew(params)
        this.tableData = res.data
        this.initTableData()
        const res2 = await phoneRate(params)
        this.chartData = res2.data.totalCallAndRate
        this.initChartData()
      },
      initTableData() {
        if (this.tableData.length > 0) {
          this.tableData[0].rowOne = true
          this.tableData[2].rowThree = true
          let passRate = ''
          let answerRate = ''
          if (this.tableData[0].toStation === 0) {
            passRate = 0
            answerRate = 0
          } else {
            passRate = ((this.tableData[0].toStationNoqueue / this.tableData[0].toStation) * 100).toFixed(2) + '%'
            answerRate = (this.tableData[1].toStation / this.tableData[0].toStation * 100).toFixed(2) + '%'
          }
          this.tableData[0].passRate = passRate
          this.tableData[2].answerRate = answerRate
        }
      },
      initChartData() {
        this.xData = this.chartData.map((item) => item.happendHour)
        if (this.type === 'today' || !this.type) {
          this.xData = ['0-1点', '1-2点', '2-3点', '3-4点', '4-5点', '5-6点', '6-7点', '7-8点', '8-9点', '9-10点', '10-11点', '11-12点', '12-13点', '13-14点', '14-15点', '15-16点', '16-17点', '17-18点', '18-19点', '19-20点', '20-21点', '21-22点', '22-23点', '23-00点']
          const answerRate = []
          const passRate = []
          const totalCallIn = []
          for (let i = 0; i < this.chartData.length; i++) {
            const item = this.chartData[i]
            const preItem = this.chartData[i - 1]
            if (i === 0) {
              totalCallIn.push(item.totalCallIn)
              if (item.toStation !== 0) {
                answerRate.push(((item.toStationTalk / item.toStation) * 100).toFixed(2))
              } else {
                answerRate.push(0)
              }
              if (item.toStationNoqueue > 0) {
                passRate.push(((parseInt(item.toStationNoqueue) / item.toStation) * 100).toFixed(2))
              } else {
                passRate.push(0)
              }
            } else {
              if (item.totalCallIn > 0) {
                totalCallIn.push(item.totalCallIn - preItem.totalCallIn)
              } else {
                totalCallIn.push(0)
              }
              if ((item.toStation - preItem.toStation) > 0) {
                answerRate.push(((item.toStationTalk - preItem.toStationTalk) / (item.toStation - preItem.toStation) * 100).toFixed(2))
              } else {
                answerRate.push(0)
              }
              if ((item.toStation - preItem.toStation) > 0) {
                passRate.push(((parseInt(item.toStationNoqueue) - parseInt(preItem.toStationNoqueue)) / (item.toStation - preItem.toStation) * 100).toFixed(2))
              } else {
                passRate.push(0)
              }
            }
          }
          this.yData1 = totalCallIn
          this.yData2 = answerRate
          this.yData3 = passRate
        } else {
          this.yData1 = this.chartData.map((item) => item.totalCallIn)
          this.yData2 = this.chartData.map((item) => {
            if (item.toStation !== 0) {
              return ((item.toStationTalk / item.toStation) * 100).toFixed(2)
            } else {
              return 0
            }
          })
          this.yData3 = this.chartData.map((item) => {
            if (parseInt(item.toStationNoqueue) !== 0) {
              return ((parseInt(item.toStationNoqueue) / item.toStation) * 100).toFixed(2)
            } else {
              return 0
            }
          })
        }
        this.$nextTick(() => {
          this.initChart()
        })
      },
      arraySpanMethod({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 2) {
          if (columnIndex === 1) {
            return [1, 4]
          }
          if (columnIndex === 2) {
            return [0, 0]
          }
          if (columnIndex === 3) {
            return [0, 0]
          }
          if (columnIndex === 4) {
            return [0, 0]
          }
        }
      },
      initChart() {
        this.chart = echarts.init(this.$refs.echart)
        this.options = {
          color: ['#8ECC75', '#EE6666', '#5470C6'],
          title: {
            show: true,
            text: (this.type === 'today' || !this.type) ? '每小时数据统计图' : '每日数据统计'
          },
          grid: {
            x: 50,
            x2: 50
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: '#999'
              }
            },
            formatter: function(params) {
              var relVal = params[0].name
              for (var i = 0, l = params.length; i < l; i++) {
                if (params[i].seriesName !== '呼入电话总数') {
                  relVal += '<br/>' + params[i].marker + params[i].seriesName + ': ' + params[i].value + '%'
                } else {
                  relVal += '<br/>' + params[i].marker + params[i].seriesName + ': ' + params[i].value
                }
              }
              return relVal
            }
          },
          legend: {
            data: ['呼入电话总数', '应答率', '直通率']
          },
          xAxis: [
            {
              type: 'category',
              data: this.xData,
              axisPointer: {
                type: 'shadow'
              },
              axisLabel: { // 设置x轴的字
                show: true,
                interval: 0, // 使x轴横坐标全部显示
                rotate: (this.type === 'today' || !this.type) ? 30 : 0
              }
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '呼入数量',
              min: 0
            },
            {
              type: 'value',
              name: '百分比',
              min: 0,
              max: 100,
              axisLabel: {
                formatter: '{value} %'
              }
            }
          ],
          series: [
            {
              name: '呼入电话总数',
              type: 'bar',
              barWidth: 20,
              markPoint: {
                data: [
                  { type: 'max', name: 'Max' },
                  { type: 'min', name: 'Min' }
                ]
              },
              label: {
                show: true,
                position: 'top'
              },
              data: this.yData1
            },
            {
              name: '应答率',
              type: 'line',
              yAxisIndex: 1,
              label: {
                show: true,
                position: 'top',
                formatter: function(data) {
                  return data.data + '%'
                }
              },
              data: this.yData2
            },
            {
              name: '直通率',
              type: 'line',
              yAxisIndex: 1,
              label: {
                show: true,
                position: 'top',
                formatter: function(data) {
                  return data.data + '%'
                }
              },
              data: this.yData3
            }
          ]
        }
        this.chart.setOption(this.options)
        addResizeListener(this.$refs.echart, this.doResize)
      },
      doResize() {
        this.chart && this.chart.resize()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .app-page {
    height: auto !important;
  }
  .row-cell {
    display: flex;
    justify-content: space-around;
    .cell-l {
      width: 50%;
      padding: 0;
      text-align: center;
      border-right: 1px solid #EBEEF5;
    }
    .cell-r {
      width: 50%;
      padding: 0;
      text-align: center;
    }
  }
  .red {
    color: #F56C6C;
  }
  .echart {
    width: 100%;
    height: 400px;
    margin-top: 30px;
  }
</style>
